package com.cdivtc.management.service;

import com.cdivtc.management.dao.FilesimgurlMapper;
import com.cdivtc.management.dao.FilesurlMapper;
import com.cdivtc.management.pojo.Bo.ZipFile;
import com.cdivtc.management.pojo.Filesimgurl;
import com.cdivtc.management.pojo.Filesurl;
import com.cdivtc.management.pojo.ResultFileUrl;
import com.cdivtc.management.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UploadService {
    @Autowired
    private FastDFSClient dfsClient;
    @Autowired
    private Office2PDF office2PDF;
    @Autowired
    private PdfToImage pdfToImage;
    @Autowired
    private FilesurlMapper filesurlMapper;
    @Autowired
    private IdWorker idWorker;

    @Autowired
    private FilesimgurlMapper filesimgurlMapper;
    @Autowired
    private ZipUtil zipUtil;

    //    将word  excel 生成图片
    public synchronized List<String> officeToImage(MultipartFile file, String fileId) throws IOException {
        List<String> imagelist = new ArrayList<>();
        ByteArrayOutputStream outputStream = office2PDF.Word2Pdf(file.getInputStream(), file.getOriginalFilename());
        List<ByteArrayOutputStream> pngoutlist = pdfToImage.pdf2png(new ByteArrayInputStream(outputStream.toByteArray()), "png");

        for (int i = 0; i < pngoutlist.size(); i++) {
            String pdf = dfsClient.uploadpdfimg(pngoutlist.get(i).toByteArray(), "png");
//            将文件地址存入数据库
            System.out.println("pdf = " + pdf);
            Filesimgurl filesimgurl = new Filesimgurl();
            filesimgurl.setId(idWorker.nextId() + "");
            filesimgurl.setListurl(StaticString.url + pdf);
            filesimgurl.setFileid(fileId);
            filesimgurlMapper.insert(filesimgurl);

            imagelist.add(pdf);
            //dfsClient.deleteFile(pdf);
        }
        return imagelist;
    }

    public Filesurl stuDoTaskUploadfile(MultipartFile file) throws IOException {
        String substring = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        String uploadFile = StaticString.url + dfsClient.uploadFile(file);
        Filesurl filesurl = new Filesurl();
        String s = idWorker.nextId() + "";
        filesurl.setId(s);

        if (substring.equals("doc")
                || substring.equals("docx")
                || substring.equals("xlsx")
                || substring.equals("xls")
                || substring.equals("pdf")) {
            new Thread(() -> {
                try {
                    officeToImage(file, s);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }
        filesurl.setUrl(uploadFile);
        filesurl.setType(substring);
        filesurl.setUserId("stu");
        filesurl.setTaskId("stu");
        filesurl.setFilenam(file.getOriginalFilename());
        int insert = filesurlMapper.insert(filesurl);
        return filesurl;
    }

    public Filesurl uploadfile(MultipartFile file, String userId) throws IOException {
        String substring = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        String uploadFile = StaticString.url + dfsClient.uploadFile(file);
        Filesurl filesurl = new Filesurl();
        String s = idWorker.nextId() + "";
        filesurl.setId(s);
        if (substring.equals("doc")
                || substring.equals("docx")
                || substring.equals("xlsx")
                || substring.equals("xls")
                || substring.equals("pdf")) {
            new Thread(() -> {
                try {
                    officeToImage(file, s);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }
        filesurl.setUrl(uploadFile);
        filesurl.setType(substring);
        filesurl.setUserId(userId);
        filesurl.setFilenam(file.getOriginalFilename());
        int insert = filesurlMapper.insert(filesurl);
        return filesurl;
    }

    public void deletefile(String fileurl) {
        dfsClient.deleteFile(fileurl);

//        Filesurl filesurl = new Filesurl();
//        filesurl.setUrl(fileurl);
//        filesurlMapper.delete(filesurl);

        Example example = new Example(Filesurl.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("url", fileurl);
        List<Filesurl> filesurls = filesurlMapper.selectByExample(example);
        for (Filesurl filesurl : filesurls) {
            String id = filesurl.getId();
            Example example1 = new Example(Filesimgurl.class);
            Example.Criteria criteria1 = example1.createCriteria();
            criteria1.andEqualTo("fileid", id);
            filesimgurlMapper.deleteByExample(example1);
        }

        int i = filesurlMapper.deleteByExample(example);

    }

    //删除所有文件
    public void deletefilebeach() {
        List<Filesimgurl> filesimgurls = filesimgurlMapper.selectAll();
        for (Filesimgurl f : filesimgurls) {
            dfsClient.deleteFile(f.getListurl());
            filesimgurlMapper.delete(f);
        }
        List<Filesurl> filesurls = filesurlMapper.selectAll();
        for (Filesurl f : filesurls) {
            dfsClient.deleteFile(f.getUrl());
            filesurlMapper.delete(f);
        }

    }


    //获取用户传的文件
    public ArrayList<ResultFileUrl> selFileUrlByTaskId(String taskId) {
        ArrayList<ResultFileUrl> resultFileUrls = new ArrayList<>();
        Example example = new Example(Filesurl.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("taskId",taskId);
        List<Filesurl> filesurls = filesurlMapper.selectByExample(example);
        for (Filesurl filesurl : filesurls) {
            ResultFileUrl resultFileUrl = new ResultFileUrl();
            if (filesurl.getType().equals("doc")
                    || filesurl.getType().equals("docx")
                    || filesurl.getType().equals("xlsx")
                    || filesurl.getType().equals("zip")
                    || filesurl.getType().equals("rar")
                    || filesurl.getType().equals("xls")) {

                Example example1 = new Example(Filesimgurl.class);
                Example.Criteria criteria1 = example1.createCriteria();
                System.out.println("filesurl.getId() = " + filesurl.getId());
                criteria1.andEqualTo("fileid", filesurl.getId());
                List<Filesimgurl> filesimgurls = filesimgurlMapper.selectByExample(example1);
                ArrayList<String> strings = new ArrayList<>();
                if (filesimgurls.size() != 0) {
                    for (Filesimgurl filesimgurl : filesimgurls) {
                        strings.add(filesimgurl.getListurl());
                        resultFileUrl.setFileImgUrl(strings);
                    }
                } else if(filesurl.getType().equals("zip")
                        || filesurl.getType().equals("rar")){
                    strings.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1577848476&di=6141edba4a98a6f8fcf30a09c96dae94&imgtype=jpg&er=1&src=http%3A%2F%2Fpic.51yuansu.com%2Fpic2%2Fcover%2F00%2F45%2F67%2F5814f4f280e61_610.jpg");
                    resultFileUrl.setFileImgUrl(strings);
                } else {
                    strings.add("https://img.zcool.cn/community/0134e656cd6d216ac7252ce662d494.gif");
                    resultFileUrl.setFileImgUrl(strings);
                }
            }
            resultFileUrl.setName(filesurl.getFilenam());
            resultFileUrl.setUrl(filesurl.getUrl());
            resultFileUrl.setFileId(filesurl.getId());
            resultFileUrl.setType(filesurl.getType());
            resultFileUrls.add(resultFileUrl);
        }
        return resultFileUrls;
    }


    //获取用户传的文件
    public ArrayList<ResultFileUrl> selAllFileUrlByUserId(String userId, String taskId) {
        ArrayList<ResultFileUrl> resultFileUrls = new ArrayList<>();
        Example example = new Example(Filesurl.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", userId);

        if(!taskId.equals("add")){//通过传的参数  判断是不是add或为空 来确定是添加还是查看
            criteria.andEqualTo("taskId", taskId);

            Example.Criteria criteria2 = example.createCriteria();
            criteria2.andEqualTo("userId", userId);
            criteria2.andIsNull("taskId");
            example.or(criteria);
            example.or(criteria2);
        }else{
            criteria.andIsNull("taskId");
        }

        System.out.println("userId = " + userId);

        List<Filesurl> filesurls = filesurlMapper.selectByExample(example);
        for (Filesurl filesurl : filesurls) {
            ResultFileUrl resultFileUrl = new ResultFileUrl();
            if (filesurl.getType().equals("doc")
                    || filesurl.getType().equals("docx")
                    || filesurl.getType().equals("xlsx")
                    || filesurl.getType().equals("zip")
                    || filesurl.getType().equals("rar")
                    || filesurl.getType().equals("xls")) {
                Example example1 = new Example(Filesimgurl.class);
                Example.Criteria criteria1 = example1.createCriteria();
                System.out.println("filesurl.getId() = " + filesurl.getId());
                criteria1.andEqualTo("fileid", filesurl.getId());
                List<Filesimgurl> filesimgurls = filesimgurlMapper.selectByExample(example1);
                ArrayList<String> strings = new ArrayList<>();
                if (filesimgurls.size() != 0) {
                    for (Filesimgurl filesimgurl : filesimgurls) {
                        strings.add(filesimgurl.getListurl());
                        resultFileUrl.setFileImgUrl(strings);
                    }
                } else if(filesurl.getType().equals("zip")
                        || filesurl.getType().equals("rar")){
                    strings.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1577848476&di=6141edba4a98a6f8fcf30a09c96dae94&imgtype=jpg&er=1&src=http%3A%2F%2Fpic.51yuansu.com%2Fpic2%2Fcover%2F00%2F45%2F67%2F5814f4f280e61_610.jpg");
                    resultFileUrl.setFileImgUrl(strings);
                }else{
                    strings.add("https://img.zcool.cn/community/0134e656cd6d216ac7252ce662d494.gif");
                    resultFileUrl.setFileImgUrl(strings);
                }
            }
            resultFileUrl.setName(filesurl.getFilenam());
            resultFileUrl.setUrl(filesurl.getUrl());
            resultFileUrl.setFileId(filesurl.getId());
            resultFileUrl.setType(filesurl.getType());
            resultFileUrls.add(resultFileUrl);
        }
        return resultFileUrls;
    }

    //下载文件
    public void download(HttpServletResponse res, String file) throws Exception {
        System.out.println(" 我是没有修改之后的下载文件");
        Date d = new Date();
        String[] split = file.split("/");
        res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");
        String downloadFileName = URLEncoder.encode(split[split.length - 1], "UTF-8");
        res.setHeader("Content-Disposition", "attachment;filename=" + downloadFileName);
//        使用原生的网络请求 获取
        URL url = new URL(file);
        URLConnection connection = url.openConnection();
        connection.connect();
        byte[] buff = new byte[1024];
        BufferedInputStream input = new BufferedInputStream(connection.getInputStream());

        int len = 0;
        BufferedOutputStream os = new BufferedOutputStream(res.getOutputStream());
        while ((len = input.read(buff)) != -1) {
            os.write(buff, 0, len);
        }
        System.out.println("success");
        input.close();
        os.close();
/*
        byte[] bytes = dfsClient.downloadFile(file);
        System.out.println(" 已经将文件转化为byte  共耗时" +(new Date().getTime()-d.getTime()));
        String[] split = file.split("/");
        res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");
        String downloadFileName = URLEncoder.encode(split[split.length - 1],"UTF-8");
        res.setHeader("Content-Disposition", "attachment;filename=" +downloadFileName );
        byte[] buff = new byte[1024];
        ByteArrayInputStream bis = null;
        OutputStream os = null;
        try {
            os = res.getOutputStream();
            bis = new ByteArrayInputStream(bytes);
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            ;
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {

                }
            }
        }
        System.out.println("success");

*/
    }
    //    批量下载文件
    public String downloadbatch(HttpServletResponse response, List<String> urls,String filesname) throws IOException {

        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream;charset=utf-8");
        String downloadFileName = URLEncoder.encode(filesname+".zip", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + downloadFileName);
        List<ZipFile> fileList = new ArrayList<>();
        for (String url : urls) {
            String[] split = url.split("/");
            BufferedInputStream urlBUff = getUrlBUff(url);
            ZipFile zipFile = new ZipFile();
            zipFile.setName(split[split.length - 1]);
            zipFile.setInputStream(urlBUff);
            fileList.add(zipFile);
        }
        try {


            zipUtil.toZip(fileList, response.getOutputStream());

        } catch (IOException e) {
            e.printStackTrace();
            return "下载失败";
        }
        return "下载失败";
    }

    public BufferedInputStream getUrlBUff(String file) throws IOException {
        URL url = new URL(file);
        URLConnection connection = url.openConnection();
        connection.connect();
        return new BufferedInputStream(connection.getInputStream());

    }

    public String uploadImg(MultipartFile file,String userId) throws IOException {
        String imageurl = dfsClient.uploadFace(file);
        imageurl = "http://119.23.29.217/" +imageurl;
        String substring = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        Filesurl filesurl = new Filesurl();
        filesurl.setId(idWorker.nextId()+"");
        filesurl.setUrl(imageurl);
        filesurl.setType(substring);
        filesurl.setUserId(userId);
        filesurl.setTaskId("11223343");
        filesurl.setFilenam(file.getOriginalFilename());
        int insert = filesurlMapper.insert(filesurl);
        return imageurl;
    }

    public void deleteByTaskNull(String uid) {
        Example example = new Example(Filesurl.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId",uid);
        List<Filesurl> select = filesurlMapper.selectByExample(example);
        for (Filesurl filesurl1 : select) {

            if (filesurl1.getTaskId() == null || "".equals(filesurl1.getTaskId())) {
                System.out.println("filesurl1 = " + filesurl1);
                deletefile(filesurl1.getUrl());
                filesurlMapper.deleteByPrimaryKey(filesurl1.getId());
            }
        }

    }

}
